import { getInfo, login, logout } from '@/api/login';
import { getToken, removeToken, setToken } from '@/utils/auth';
import defAva from '@/assets/images/profile.jpg';
import { defineStore } from 'pinia';
import { isRelogin } from '@/utils/request';
import { mailLogin, mailRegister } from '@/api/business/user';
import router from '@/router';

const useUserStore = defineStore('user', {
    state: (): {
        posts?: string[];
        postIds?: number[];
        token?: string;
        name: string;
        avatar: string;
        roles: any[];
        permissions: string[];
        userInfo?: any;
        countInfo?: any;
        readAndNotReadCount: { read: number, notRead: number }
    } => ({
        posts: [],
        postIds: [],
        token: getToken() || '',
        name: '',
        avatar: '',
        roles: [],
        permissions: [],
        userInfo: {},
        countInfo: {},
        readAndNotReadCount: { read: 0, notRead: 0 }
    }),
    actions: {
        setUserInfo(userInfo: any) {
            this.userInfo = userInfo;
        },
        /*邮箱注册*/
        mailRegister(userInfo: { email: string; code: string; title: string, password: string }) {
            return new Promise((resolve, reject) => {
                mailRegister(userInfo).then((res: any) => {
                    setToken(res.token);
                    this.token = res.token;
                    this.getInfo();//获取用户信息
                    isRelogin.show = false;
                    resolve(1);
                }).catch(error => {
                    reject(error);
                });
            });
        },
        /*邮箱登录*/
        mailLogin(userInfo: { email: string; code: string; title: string }) {
            return new Promise((resolve, reject) => {
                mailLogin(userInfo).then((res: any) => {
                    setToken(res.token);
                    this.token = res.token;
                    this.getInfo();//获取用户信息
                    isRelogin.show = false;
                    resolve(1);
                }).catch(error => {
                    reject(error);
                });
            });
        },
        // 登录
        login(userInfo: { username: string; password: string; code: string; uuid: string }) {
            const username = userInfo.username.trim();
            const password = userInfo.password;
            const code = userInfo.code;
            const uuid = userInfo.uuid;
            return new Promise((resolve, reject) => {
                login(username, password, code, uuid)
                    .then((res: any) => {
                        setToken(res.token);
                        this.token = res.token;
                        this.getInfo();//获取用户信息
                        isRelogin.show = false;
                        if (isRelogin.redirect) {
                            router.push(isRelogin.redirect).then(() => {
                                isRelogin.redirect = '';
                            });
                        }
                        resolve(1);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },
        // 获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfo()
                    .then((res: any) => {
                        const user = res.user;
                        const avatar =
                            user.avatar === '' || user.avatar == null
                                ? defAva
                                : import.meta.env.VITE_APP_BASE_API + user.avatar;

                        if (res.roles && res.roles.length > 0) {
                            // 验证返回的roles是否是一个非空数组
                            this.roles = res.roles;
                            this.permissions = res.permissions;
                        } else {
                            this.roles = ['ROLE_DEFAULT'];
                        }
                        this.name = user.userName;
                        this.avatar = avatar;
                        this.userInfo = user;
                        this.posts = res.posts;
                        this.postIds = res.postIds;
                        this.countInfo = res.countInfo;
                        this.readAndNotReadCount = res.readAndNotReadCount;
                        resolve(res);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },
        // 退出系统
        logOut() {
            return new Promise((resolve, reject) => {
                logout()
                    .then(() => {
                        this.name = '';
                        this.avatar = '';
                        this.token = '';
                        this.roles = [];
                        this.permissions = [];
                        this.userInfo = {};
                        this.posts = [];
                        removeToken();
                        resolve(1);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        }
    },
    getters: {
        /*是否已经登录*/
        isLogin(): boolean {
            return this.token
                &&
                this.token !== ''
                &&
                this.userInfo
                &&
                JSON.stringify(this.userInfo) !== '{}';
        }
    }
});

export default useUserStore;
